<script setup>
import routingDataJson from '../data/data.json'
import { ArrowLeft } from '@element-plus/icons-vue'
import StationModel from '../components/BaseStation.vue';
import {ref, onMounted, onBeforeMount} from 'vue'
import html2canvas from 'html2canvas'
import { formPost, get, post } from '../js/http';
import router from '../router';

const routingData = ref(routingDataJson);
const configInfo = ref({})
const drawer = ref(false)
const drawerDirection = ref('ltr')
const currentStation = ref({})
const historyStation = ref({})
const currentOptionPos = ref('')
const leftStationIndex = ref(0);
const rightStationIndex = ref(1);
const showSelectStation = ref(false);
const currentChoose = ref('')

const leftCom = ref()
const rightCom = ref()

const props = defineProps({projectId:String,routingId:String})
const stationList = ref([])

const getStationList = () => {
    console.log(props.projectId)
    get('/routing/station/byProjectId',{keyword:'', projectId: props.projectId}).then(res=>{
        stationList.value = res.data
    })
}

const showSettingData = (idName) => {
    getStationList();
    currentOptionPos.value = idName;
    if(idName == 'left'){
        drawerDirection.value = 'rtl';
        currentStation.value = routingData.value[leftStationIndex.value];
        let tempJson = JSON.stringify(currentStation.value);
        historyStation.value = JSON.parse(tempJson);
    }else{
        drawerDirection.value = 'ltr';
        currentStation.value = routingData.value[rightStationIndex.value];
        let tempJson = JSON.stringify(currentStation.value);
        historyStation.value = JSON.parse(tempJson);
    }
    drawer.value = true
}

const reset = () => {
    let tempJson = JSON.stringify(historyStation.value);
    currentStation.value = JSON.parse(tempJson);
    if(currentOptionPos.value == 'left'){
        routingData.value[leftStationIndex.value] = JSON.parse(tempJson)
    }else{
        routingData.value[rightStationIndex.value] = JSON.parse(tempJson)
    }
}

const downlaodPic = () => {
    html2canvas(document.getElementById('box'),{
        scale:2,
        ignoreElements:(elemnet)=>{
            if(elemnet.classList[0] == 'toolbar')
            return true;
        },
        backgroundColor: localStorage.getItem('vueuse-color-scheme') == 'dark' ? 'black' : 'white'
    }).then((canvas)=>{
        var link = document.createElement("a");
        var imgData =canvas.toDataURL({format: 'png', quality:1, width:2000, height:400});
        var blob = dataURLtoBlob(imgData);
        var objurl = URL.createObjectURL(blob);
        link.download = routingData.value[leftStationIndex.value].name+"-"+routingData.value[rightStationIndex.value].name+".png";
        link.href = objurl;
        link.click();
        
        function  dataURLtoBlob(dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        }
    })
    
}

const saveRouting = () => {
    let leftRoute = leftCom.value.getSelectValue();
    let rightRoute = rightCom.value.getSelectValue();
    console.log(leftRoute, rightRoute)
    if(leftRoute == null || rightRoute == null){
        ElMessageBox.alert('请选择交路后提交','提示',{type:'warning', confirmButtonText:'确认'});
        return;
    }
    rightCom.value.getSelectValue();
    let routingSetting = {}
    if(props.routingId != 0){
        routingSetting.id = props.routingId;
    }
    routingSetting.leftIndex = leftStationIndex.value;
    routingSetting.rightIndex = rightStationIndex.value;
    routingSetting.projectId = props.projectId;
    routingSetting.routingName = routingData.value[leftStationIndex.value].name + "至" +routingData.value[rightStationIndex.value].name;
    routingSetting.leftRoute = leftRoute;
    routingSetting.rightRoute = rightRoute;
    let routingInfo = [routingData.value[leftStationIndex.value],routingData.value[rightStationIndex.value]];
    routingSetting.routingInfo = JSON.stringify(routingInfo);
    post('/routing/setting', routingSetting).then(res=>{
        if(res.status){
            html2canvas(document.getElementById('box'),{
                scale:2,
                ignoreElements:(elemnet)=>{
                    if(elemnet.classList[0] == 'toolbar')
                    return true;
                }
            }).then((canvas)=>{
                let file = castToFile(canvas);
                let id = res.data;
                let formData = new FormData();
                formData.append('file',file);
                formData.append('id',id);
                formPost('/routing/setting/uploadImg',formData).then(res2=>{
                    ElMessage({type: res2.data.status?'success':'error', message: res2.data.message});
                })
            })
        }else{
            ElMessage({type:'error', message: res.message});
        }
    })
}

const castToFile = (canvas) => {
    var dataurl = canvas.toDataURL("image/png");
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    var file = new File([u8arr], '交路图', {type: mime});
    return file;
}

const chooseStation = (type) => {
    currentChoose.value = type;
    showSelectStation.value = true;
}

const handleChooseStation = (index) => {
    if(currentChoose.value == 'left'){
        leftStationIndex.value = index;
    }else{
        rightStationIndex.value = index;
    }
    showSelectStation.value = false;
}

const back = () => {
    router.go(-1);
}


onMounted(()=>{
    if(props.routingId != 0){
        get('/routing/setting/byId',{id: props.routingId}).then(res=>{
            if(res.status){
                leftStationIndex.value = res.data.leftIndex;
                rightStationIndex.value = res.data.rightIndex;
                let obj = JSON.parse(res.data.routingInfo)
                routingData.value[leftStationIndex.value].name = obj[0].name
                routingData.value[rightStationIndex.value].name = obj[1].name
                routingData.value[leftStationIndex.value].tracks = obj[0].tracks
                routingData.value[rightStationIndex.value].tracks = obj[1].tracks
                setTimeout(() => {
                    leftCom.value.setSelectValue(res.data.leftRoute);
                    rightCom.value.setSelectValue(res.data.rightRoute);    
                }, 200);
                
            }else{
                ElMessageBox.alert(res.message,'错误',{type:'error', confirmButtonText:'确认'});
                router.go(-1);
            }
        })
    }
})

</script>

<template>
    <div class="generate">
        <div class="toolbar">
            <el-button @click="back" :icon="ArrowLeft">返回</el-button>
            <el-button type="primary" @click="chooseStation('left')">选择左侧站型</el-button>
            <el-button type="primary" @click="chooseStation('right')">选择右侧站型</el-button>
            <el-button type="success" @click="saveRouting">保存交路</el-button>
            <el-button type="info" @click="downlaodPic">下载交路图片</el-button>
        </div>
        <div style="height: calc(100vh - 200px); display: flex; flex-direction: column; justify-content: center; align-items: center;">
            <div class="box" id="box">
                <StationModel ref="leftCom" @setting-data="showSettingData" class="model left" id-name="left" :station-name="routingData[leftStationIndex].name" :config-info="configInfo" :routing-data="routingData[leftStationIndex]"/>
                <StationModel ref="rightCom" @setting-data="showSettingData" class="model right" id-name="right" :station-name="routingData[rightStationIndex].name" :config-info="configInfo" :routing-data="routingData[rightStationIndex]"/>
            </div>
        </div>
        
        <el-drawer
            v-model="drawer"
            :title="currentStation.name+'配置'"
            :direction="drawerDirection"
        >
            <el-form label-position="top">
                <el-form-item label="车站名称">
                    <el-select filterable v-model="currentStation.name" style="width: 100%;">
                        <el-option v-for="item in stationList" :key="item.id" :label="item.stationName" :value="item.stationName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="车站名称位置">
                    <div class="form-line">
                        <label>X坐标: </label>
                        <el-input style="width: 100px;" placeholder="横坐标" type="Number" v-model="currentStation.titlePosition[0]"></el-input>
                        <label>Y坐标: </label>
                        <el-input style="width: 100px;" placeholder="纵坐标" type="Number" v-model="currentStation.titlePosition[1]"></el-input>
                    </div>
                    
                </el-form-item>
                <el-form-item label="站台位置">
                    <div class="form-line" v-for="(item, index) in currentStation.stationReact" :key="index">
                        <label>X坐标: </label>
                        <el-input style="width: 100px;" placeholder="横坐标" type="Number" v-model="item[0]"></el-input>
                        <label>Y坐标: </label>
                        <el-input style="width: 100px;" placeholder="纵坐标" type="Number" v-model="item[1]"></el-input>
                    </div>
                    
                </el-form-item>
                <el-form-item label="转换轨配置">
                    <div v-for="(item,index) in currentStation.tracks" :key="index">
                        <div class="form-line">
                            <label>Track {{ index }}</label>
                            <el-input style="width: 100px;" v-model="item.name"></el-input>
                        </div>
                        
                    </div>
                </el-form-item>
            </el-form>
            <div class="option-btn">
                <el-button type="info" style="width: 100px;" @click="reset">重置</el-button>
                <el-button type="primary" style="width: 100px;" @click="drawer=false">完成</el-button>
            </div>
        </el-drawer>
        <el-drawer
            v-model="showSelectStation"
            title="站型选择"
            :direction="currentChoose=='left'?'rtl':'ltr'"
        >
            <div class="stationListBox">
                <div v-for="(item,index) in routingData" :key="index" class="stationItem" @click="handleChooseStation(index)">
                    <StationModel :not-show-setting="true" @setting-data="showSettingData" class="model" :id-name="'temp'+index" :station-name="item.name" :config-info="configInfo" :routing-data="item"/>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<style scoped>
.generate{
    width: 100%;
}
.box{
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
    max-width: 2000px;
    border: 1px solid gainsboro;
}
.model{
    border: none
}
.left{
    border-right: none;
}
.right{
    border-left: none;
}
label{
    font-size: 14px;
    padding: 0 10px;
}
.form-line{
    margin: 5px;
}
.option-btn{
    width: 100%;
    margin-top: 20px;
    text-align: right;
    position: absolute;
    bottom: 20px;
    right: 20px;
}
.toolbar{
    padding: 10px;
}
.stationItem{
    width: calc(100% - 20px); 
    margin-right: 10px; 
    cursor: pointer;
    border: 1px solid gray;
    margin: 10px;
}
.stationItem:hover{
    background-color: var(--el-color-info-light-9);
}
.stationListBox{
    /* max-height: 500px; */
    overflow: auto;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
}
</style>